package com.customization.unionpay.market.workflowaction;

import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.contract.serivce.impl.ContractBaseServiceImpl;
import com.customization.unionpay.market.maketEnum.InstructionEnum;
import com.customization.unionpay.market.util.FormDataUtils;
import weaver.generalledger.action.ZzgdExecuteInstrucitonAction;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.OverTimeSetBean;
import weaver.workflow.request.RequestManager;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author sjm
 * @description 营销事项申请表单节点action
 */
public class MarketingApplicationAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketingApplicationAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        log.info("进入申请单发起和回退！");
        OverTimeSetBean overTimeBean = new OverTimeSetBean();

        RequestManager rm = requestInfo.getRequestManager();
        try {
            com.customization.unionpay.contract.serivce.impl.ContractBaseServiceImpl contractBaseService = new ContractBaseServiceImpl();

            String src = rm.getSrc();
            int nodeId = rm.getNodeid();
            // 流程表单id
            int formId = rm.getFormid();

            Map<String, Object> allFormData = com.customization.unionpay.market.util.FormDataUtils.getAllFormData(requestInfo);

            Map<String, String> mainMap = (Map<String, String>) allFormData.get("mainMap");
            // 所有明细表的值
            Map<String, Map<String, Map<String, String>>> detailMap = (Map<String, Map<String, Map<String, String>>>) allFormData.get("detailMap");

            // 主 业务日期        ywrq
            String ywrq = mainMap.get("ywrq");
            // 主 预算控制期      yskzq
            String yskzq = mainMap.get("yskzq");

            String ywrqStr = com.customization.unionpay.market.util.FormDataUtils.changeDateString("yyyy-MM-dd", ywrq, "yyyy");
            log.info("ywrqStr："+ywrqStr);
            String yskzqStr = com.customization.unionpay.market.util.FormDataUtils.changeDateString("yyyy-MM-dd", yskzq, "yyyy");
            log.info("yskzqStr："+yskzqStr);

            // 合同编号
            String htbh = mainMap.get("htbhwb");
            log.info("htbh："+htbh);

            // sfwdxy   是否为大协议
            String sfwdxy = mainMap.get("sfwdxy");
            String sfwdxyName = FormDataUtils.getItemName(formId, "sfwdxy", sfwdxy);
            log.info("isSfwdxy："+sfwdxyName);
            log.info("src："+src);
            if ("reject".equals(src)) {
                // 【审批中金额】流程审批退回则扣减明细行【内部出资金额】 1 提交 2 回退 3 归档 4、本次调整金额
                String[] singleHtbhs = htbh.split(",");
                log.info("htCodeLength："+singleHtbhs.length);
                if(singleHtbhs.length == 1){
                    Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                    for (String key : dt1.keySet()) {
                        Map<String, String> value = dt1.get(key);
                        // 内部出资金额
                        String nbczje = value.get("nbczje");
                        // 履约明细号
                        Integer lymxh = Integer.valueOf(value.get("lymxh"));
                        log.info("lymxh：" + lymxh);
                        contractBaseService.updateAmountFunded(2, lymxh, nbczje);
                    }
                }else if(singleHtbhs.length > 1) {
                    List<String> list = new ArrayList<>(Arrays.asList(singleHtbhs));
                    log.info("list：" + list);
                    // 返回选中合同，标记 2 已关联 3 取消关联
                    contractBaseService.syncGxStatus(list,3);
                }

                // 判断当前节点是否回退到发起节点
                if("否".equals(sfwdxyName)){
                    String instruction = "";
                    if(ywrqStr.equals(yskzqStr)){
//                        // 预算 内部出资金额	明细表    业务日期的年份=预算控制期的年份    驳回-释放占用
                        instruction = com.customization.unionpay.market.maketEnum.InstructionEnum.SFZY.toString();
                    }else {
//                        // 预算 内部出资金额	明细表    业务日期的年份≠预算控制期的年份    回-项目释放占用
                        instruction = InstructionEnum.XMSFZY.toString();
                    }
                    log.info("instruction："+instruction);
                    ZzgdExecuteInstrucitonAction zzgdExecuteInstrucitonAction = new ZzgdExecuteInstrucitonAction();
                    zzgdExecuteInstrucitonAction.setZl(instruction);
                    String execute = zzgdExecuteInstrucitonAction.execute(requestInfo);
                    if("0".equals(execute)){
                        String messageid = requestInfo.getRequestManager().getMessageid();
                        log.info("messageid："+messageid);
                        String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                        log.info("messagecontent："+messagecontent);
                        return Action.FAILURE_AND_CONTINUE;
                    }else {
                        log.info("预算调用成功！");
                    }
                }else {
                    // 当前是否大协议不为否
                    log.info("isNotBigXieyi");
                }
            } else {
                String nodeName = overTimeBean.getNodeName(nodeId);
                log.info("nodeName："+nodeName);
                if ("发起".equals(nodeName)) {
                    // 明细行【内部出资金额】写入合同明细行【审批中金额】，若流程审批退回则  扣减 1 提交 2 回退 3 归档 4、本次调整金额
                    String[] singleHtbhs = htbh.split(",");
                    log.info("htCodeLength："+singleHtbhs.length);
                    if(singleHtbhs.length == 1){

                        Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                        for (String key : dt1.keySet()) {
                            Map<String, String> value = dt1.get(key);
                            // 内部出资金额
                            String nbczje = value.get("nbczje");
                            // 履约明细号
                            Integer lymxh = Integer.valueOf(value.get("lymxh"));
                            log.info("lymxh："+lymxh);
                            contractBaseService.updateAmountFunded(1, lymxh, nbczje);
                        }
                    }else if(singleHtbhs.length > 1) {
                        List<String> list = new ArrayList<>(Arrays.asList(singleHtbhs));
                        log.info("list：" + list);
                        // 返回选中合同，标记 2 已关联 3 取消关联
                        contractBaseService.syncGxStatus(list, 2);
                    }
                }
            }
        } catch (Exception e) {
            // 异常报错是填写异常信息，阻止流程继续流转
            requestInfo.getRequestManager().setMessageid("10001");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 拼接预算参数到中间表
     * @param requestName
     * @param yskzq
     * @param yskzqStr
     * @param mainMap
     * @param detailMap
     * @param bdh                被执行单号
     * @param requestId          执行单号
     * @param tableName
     * @param id
     * @return
     * @throws Exception
     */
    public JSONObject getMarketingApplicationParamsAddMiddle(String requestName,String yskzq,String yskzqStr,Map<String, String> mainMap,Map<String, Map<String, Map<String, String>>> detailMap,String bdh,String requestId,String tableName,String id) throws Exception {

        ResourceComInfo rci = new ResourceComInfo();
        DepartmentComInfo dci = new DepartmentComInfo();
        SubCompanyComInfo scci = new SubCompanyComInfo();

        JSONObject param = new JSONObject();

        String projectCode = mainMap.get("project_code");
        String sqr = mainMap.get("sqr");

        String workcode = rci.getWorkcode(sqr);
        String lastname = rci.getLastname(sqr);

        String bzbm = mainMap.get("bzbm");

        String departmentCode = dci.getDepartmentCode(bzbm);
        String departmentname = dci.getDepartmentname(bzbm);

        String bzgs = mainMap.get("bzgs");

        String subCompanyName = scci.getSubCompanyname(bzgs);
        String subCompanyCode = scci.getSubCompanyCode(bzgs);

        String bzsy = mainMap.get("bzsy");

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        Map<String, Map<String, String>> dt1 = detailMap.get("dt1");

        for (String key : dt1.keySet()) {
            Map<String, String> value = dt1.get(key);
            String jjsx = value.get("jjsx");
            log.info("jjsx:"+jjsx);
            // 内部出资金额
            String nbczje = "".equals(value.get("nbczje")) ? "0" : (value.get("nbczje") == null ? "0" : value.get("nbczje"));
            String yszrzx = value.get("yszrzx");
            String yskm = value.get("yskm");

            // 主 项目编号                 ysxm                预算项目
            param.put("ysxm",projectCode);
            // 明细  预算科目               yskm	             预算科目
            param.put("yskm",yskm);
            // 明细  预算责任中心           zhdw	             执行单位
            param.put("zhdw",yszrzx);
            //                           ysqjn               预算期间（年）	      必传，预算入账期间加工成4位年份
            param.put("ysqjn",yskzqStr);
            // 明细                      je                   金额
            param.put("je",nbczje);
            // 主 表单号                  bzydjh               被占用单据号	     非必传，下列情况必传： 释放占用且执行,释放执行且占用、释放占用（必传）, 占用（特殊情况必传）
            param.put("bzydjh",bdh);
            // 主 表单号                  zhdjh                执行单据号        必传
            param.put("zhdjh",requestId);
            // 主 预算控制期               yskzq              预算控制期           必传，预算的入账期间
            param.put("yskzq",yskzq);
            //                           zhrq	            执行日期	           必传，当前日期
            param.put("zhrq",format);
            //                           zhdjlx	            执行单据类型	        必传
            param.put("zhdjlx","营销事项申请流程");
            // 主 申请人                  bzr                  报账人          必传，工号-姓名
            param.put("bzr",workcode+"-"+lastname);
            //                           lyxt	            来源系统	           必传，智慧财务平台
            param.put("lyxt","智慧财务平台");
            // 主 报账事由                sm	                 说明  	        必传，各报账单的主表备注字段
            param.put("sm",bzsy);
            // 主 报账部门                tdrbm                报账部门        必传，部门编码-部门名称
            param.put("tdrbm",departmentCode+"-"+departmentname);
            // 主 报账公司                szgs                 报账公司        必传，公司编码-公司名称
            param.put("szgs",subCompanyCode+"-"+subCompanyName);
            // 明细  经济事项      jjsx    economicEvent       经济事项             必传，经济事项编号
            param.put("jjsx",jjsx);
            // 明细  事项
            param.put("event","");
            // 明细  来源id
            param.put("lylc",id);
            // 明细  来源业务表名
            param.put("lyywbm",tableName);
        }

        return param;
    }

}
